/*
 * PlayerController.java
 * 
 * Created on Jun 4, 2007, 11:58:13 PM
 * 
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package pages;
import afterburner.jsp.JSP;
import java.io.IOException;
import java.util.List;
import javax.persistence.*;
import javax.servlet.http.HttpServletRequest;
import model.Player;
import afterburner.fuel.annotations.PersistenceFuel;
import afterburner.jsp.annotations.LayoutTemplate;
/**
 *
 * @author aris
 */
@LayoutTemplate("layout.jsp")
public class PlayerController extends JSP{

    
    /**
     * 
     */
    protected List<Player> players = null;
    protected Player player = null;

    
    
    
    private  EntityManager persistence = null;
    public PlayerController() {
    }

    @PersistenceFuel("league")
    public void setPersistence(EntityManager persistence) {
        this.persistence = persistence;
    }
   
    public void create() throws IOException{
        log("create 1");
        if(!isPost())return;
        log("create 2");
        String first = param("first");
        String last = param("last");
        String position = param("position");
        String age = param("age");
        player = new Player();
        player.setFirstName(first);
        player.setLastName(last);
        player.setPosition(position);
        player.setAge(Integer.parseInt(age));
        persistence.persist(player);
        
    }
    
    public void update() throws IOException{
        HttpServletRequest request = getRequest();
        String first = param("first");
        String last = param("last");
        String position = param("position");
        String age = param("age");
        long id = Long.parseLong(getRequest().getParameter("id"));
        player = null;
        player = persistence.find(Player.class,id);
        
        if(player != null){
            player.setFirstName(first);
            player.setLastName(last);
            player.setPosition(position);
            player.setAge(Integer.parseInt(age));
            //player = persistence.merge(player);

        }else {
            setFlash("notice","Could not find player!");
        }
        
    }
    
    public void delete() throws IOException{
        HttpServletRequest request = getRequest();
        long id = Long.parseLong(param("id"));
         Player _player = persistence.find(Player.class,id);
        persistence.remove(_player);
    }
    public void show(){
        long id = Long.parseLong(getRequest().getParameter("id"));
        player = persistence.find(Player.class,id);
        if(player == null){
            player = new Player();
        }
    }
    
    public void newPlayer(){
        player = new Player();
    }
    
    public void edit(){
        show();
    }

    
    public void list(){
         players = persistence.createQuery("select p from Player p order by p.lastName").getResultList(); 
    }
}
